<?php include_stylesheets_for_form($form) ?>
<?php include_javascripts_for_form($form) ?>
<script type="text/javascript">
// <![CDATA[
function getLabel(fieldName){
	var labels = {
	  <?php
	  $count = 0;
	  foreach($form as $formfield){
			$key = $formfield->renderName();
			$val = $formfield->renderLabelName();
			echo "'". html_entity_decode(htmlentities($key, ENT_QUOTES)) ."':'". html_entity_decode(htmlentities($val, ENT_QUOTES)) ."'". (($form->count() - 1 == $count++) ? '' : ','); 
	  }
	  ?>
	};
	return labels[fieldName];
}
</script>
<?php $form_id = Util::createGUID()?>
<?php if(!isset($buttons)) $buttons=true?>
<?php if(!isset($formAction)){
	$formAction = url_for($module.'/'.($form->getObject()->isNew() ? 'create?className='.$className : 'update').(!$form->getObject()->isNew() ? '?id='.$form->getObject()->getId().'&className='.$className : ''));
}?>
<?php if(!isset($target)){
	$target = "target=frame_$form_id";
}else{
	$target = "target=$target";
}?>

<form id="<?php echo $form_id ?>" action="<?php echo $formAction ?>" method="post" <?php $form->isMultipart() and print 'enctype="multipart/form-data" ' ?> tmt:validate = "true" tmt:callback="errorOnLabels" class="defaultForm" <?php echo $target;?>>
<?php if (!$form->getObject()->isNew()): ?>
<input type="hidden" name="sf_method" value="put" />
<?php endif; ?>


<?php echo $form->renderGlobalErrors() ?>
<?php if($default=='true'):?>
			<?php  if ($form->isCSRFProtected()) : ?> 
			  <?php echo $form['_csrf_token']; ?> 
			<?php endif; ?>							
			<?php echo $form['id']; ?>
		<?php if(empty($objDef)) $objDef = new objectDef($className); ?>			
		<?php if($objDef->description): ?>
			<fieldset>
				<legend><?php echo __("General Information"); ?></legend>
		  			<div class="description">
		  				<?php echo $objDef->description?>
		  			</div>
		  	</fieldset>
		<?php endif;?>
		  <?php 
	   	  $section = '';
		  foreach($objDef->attributes as $fieldName => $att):?>
		    <?php if($att['type']!='function'):?>
		        <?php if($section != $att['section'] and $att['show'] and !in_array($fieldName,$form->hiddenFields) ):?>
		        	<?php if($section !=''):?>
		        		</fieldset>
		        	<?php endif;?>
		            <fieldset id="<?php echo Util::stripAccents2($att['section'], true)?>"><legend><?php echo __($att['section'],null,'forms')?></legend>
		            <?php $section = $att['section']?>
		  		<?php endif;?>
			    <?php if($att['type']!='BOList'):?>
		  			<?php echo $objDef->renderAttributeWidget($form, $fieldName, $hide); ?>
			    <?php else:?>
					  <?php if($att['show'] and !in_array($fieldName,$form->hiddenFields)):?>
					  <?php $relatedClass = $att['relatedClass']; $relatedObjDef = new objectDef($relatedClass);?>
					  <fieldset><legend><?php echo $att['label']?></legend>
					  <span class="formHint"><?php echo $att['help'] ?> </span>
					  <?php if($form->getObject()->isNew()){$paramId='';}else{$paramId='&ownerId='.$form->getObject()->id;}?>
					  <div id="list_<?php echo $fieldName?>"></div>
					  		<?php $boLists[$fieldName] = $relatedClass?>
					  </fieldset>
					  <?php endif;?>
				  <?php endif;?> 
		  	<?php endif;?> 	
		  <?php endforeach;?>
		  </fieldset>
<?php endif;?>


<?php 
if(isset($form->extraTemplates)){
	if(is_array($form->extraTemplates)){
		foreach($form->extraTemplates as $template){
			include_partial($template, array('form'=>$form)); 
		}
	}
}
?>
 <?php if($buttons):?>
		  	<div id="buttons">
				  <a id="confirm" style="float:right;" onclick="submitForm('<?php echo  $form_id;?>');" href="#">
			      <img src="/images/icons/64/confirm.png" title="<?php echo __('Save')?> " />
			      </a>
			      <?php if($form->getObject()->isNew()):?>
			      		<a id="deleteItem" style="float:right;" onclick="$.fancybox.close();" href="#">
				      	 	<img src="/images/icons/64/delete.png" title="<?php echo __('Delete')?> "/>
				      	</a>
			      <?php else:?>
				      <?php if($objDef->canBeDeleted):?>
				      	 <a id="deleteItem" style="float:right;" onclick="deleteItem('<?php echo get_class($self); ?>', ', <?php echo $self->id;?>);" href="#">
				      	 	<img src="/images/icons/64/delete.png" title="<?php echo __('Delete')?> "/>
				      	 </a>
				      <?php endif;?>
				  <?php endif;?>    
			</div>
			
		 <?php endif;?>
</form>
<div style="float:none; width:100%;"></div>
<?php if(isset($boLists)):?>
<?php //For each items list, we must create a div to contain the form, and we must retrive the list of existing items.?>
<?php foreach($boLists as $fieldName => $class): ?>

	<div id="<?php echo $fieldName.'Form'?>" class="editItemForm" style="display:none"></div>
	
	<script type="text/javascript">
		xhr<?php print $fieldName?> = getXmlHttpRequest2();
		xhr<?php print $fieldName?>.onreadystatechange = function()
		{
			if(xhr<?php print $fieldName?>.readyState == 4 && xhr<?php print $fieldName?>.status == 200)
			{
				var htmlContent = xhr<?php print $fieldName?>.responseText;
				document.getElementById("list_<?php print $fieldName?>").innerHTML = htmlContent;
			}
		};

		xhr<?php print $fieldName?>.open("POST","<?php print url_for($module.'/getViewItems'); ?>",true);
		xhr<?php print $fieldName?>.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
		xhr<?php print $fieldName?>.send("ownerClass=<?php print get_class($form->getObject())?>&ownerId=<?php print $form->getObject()->getId()?>&fieldName=<?php print $fieldName?>&className=<?php print $class?>");

	
	</script>
<?php endforeach;?>
<?php endif;?>
	<?php if($objDef->hasAttach):?>
		<?php include_partial('attachments/form', array( 'form' => $formAttach)) ?>
	<?php endif;?>
	<iframe name="frame_<?php echo $form_id;?>" src="#" style="width:0;height:0;border:0px solid #fff;"></iframe>
<script type="text/javascript">

function showForm(className,fieldName, id){
	
	/*		
	 *	Il faut trouver une alternative a ce inactivation. Le probleme est que s'il y avait un champ seul lecture
	 *  il devient modifiable. 		
	 */	
	/*for(i=0;i<objElems.length;i++){
	   objElems[i].disabled = true;
	}*/
	/*$('#myForm').fadeTo("fast", 0.5);*/
	getXmlHttpRequest();
	idDiv = fieldName+'Form';
	xhr.open("POST","<?php print url_for('defaultViewer/newAjax'); ?>",false);
	xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
	xhr.send("className="+className+"&idDiv="+idDiv+"&fieldName="+fieldName+'&id='+id);
	var textForm = xhr.responseText;
	document.getElementById(idDiv).innerHTML=textForm;
	document.getElementById(idDiv).style.display = "block";
	scroll(0,0);

}

function hideForm(idDiv){
	if(document.getElementById(idDiv)){
		document.getElementById(idDiv).style.display = "none";
		document.getElementById(idDiv).innerHTML='';
/*		
 *	Il faut trouver une alternative a ce inactivation. Le probleme est que s'il y avait un champ seul lecture
 *  il devient modifiable. 		
 */
 		/*for(i=0;i<objElems.length;i++){
		   objElems[i].disabled = false;
		}
		*/
		/*$('#myForm').fadeTo("fast", 1);*/
	}
}

function submitForm(idForm){
	var result = tmt.validator.validateForm(idForm);
	if(result){
		document.forms[idForm].submit();
	}
}

function renderList(className, fieldName, varResult)
{	
	
	getXmlHttpRequest();
	xhr.open("POST","<?php print url_for('defaultViewer/getViewItems'); ?>",false);
	xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
	xhr.send("ownerClass=<?php print get_class($form->getObject())?>&ownerId=<?php print $form->getObject()->getId()?>&fieldName="+ fieldName +"&className="+className);
	var htmlTable = xhr.responseText;
	document.getElementById('list_'+ fieldName).innerHTML = htmlTable;
	hideForm(fieldName+'Form');

}

function deleteItem(idDiv, className, fieldName, id)
{
	getXmlHttpRequest();
	xhr.open("POST","<?php print url_for('defaultViewer/deleteItem'); ?>",false);
	xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
	xhr.send("fieldName="+fieldName+'&id='+id);
	var html = xhr.responseText;
	if(html==""){
		varResult = 0;
	}else{
		varResult = 1;
	}
	renderList(className, fieldName, varResult);
	
}	
</script>